<?php

namespace app\batch;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Debug;
use app\models\{Peizhi, Lists, Tags, Exphone};
use think\Db;
use think\facade\Log;
use app\facade\Redis;


class Coupon extends Command
{
    protected $open = false;
    protected function configure()
    {
        $this->setName('Coupon')->setDescription('客户标签查重');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        ini_set('max_execution_time', 0);
        //优惠券过期检测
        $times = date('Y-m-d H:i:s', time() - 3 * 3600);
        $dates = date('Y-m-d', time() - 7 * 86400);
        $list = (new Peizhi())->select();
        //更新各品牌cmrid
        Log::write('----crmID更新star-----', 'coupon');
        foreach ($list as $peizhi) {
            $rdsnames = 'crmidupdatesss' . $peizhi['id'];
            $rdspeizhi = Redis::get($rdsnames);
            if ($rdspeizhi) {
                continue;
            }
            //更新各品牌crmID
            $lists = (new Lists())->whereNull('crmId')->where(['type' => $peizhi['type'], 'repeats' => 1, 'allocation' => 2, 'isdel' => 1])->limit(49)->column('phone');
            // $lists = (new Lists())->where('tagcreated', '<= time', $times)->where('createds', '>= time', $dates)->where(['type' => $peizhi['type'], 'allocation' => 2, 'isdel' => 1])->limit(49)->column('phone');
            $lists = array_filter($lists);
            if (count($lists) <= 0) {
                continue;
            }
            $phone = implode(',', $lists);
            //批量查询
            $ccdata = [
                "mobile" => $phone, //来源ID
                "maxNumsPreMobile" => 1
            ];
            $ccjsonData = json_encode($ccdata);
            // 2. 请求服务器处理
            $ccurl = "https://open.workec.com/v2/customer/queryExist";
            list($ccreturnCode, $ccreturnContent) = doPost($peizhi['cid'], $peizhi['appId'], $peizhi['appSecret'], $ccurl, $ccjsonData);
            $ccrjson = json_decode($ccreturnContent, true) ?? [];
            Log::write($ccrjson, 'coupon');
            //一个小时更新一次
            Redis::setex($rdsnames, 3600, 3600);
            if (!empty($ccrjson['code']) && $ccrjson['code'] == 200 && !empty($ccrjson['data']) && count($ccrjson['data']) > 0) {
                foreach ($ccrjson['data'] as $rjdata) {
                    if (!empty($rjdata['num']) && !empty($rjdata['mobile'])) {
                        $crmId = $rjdata['list'][0]['crmId'] ?? 0;
                        if (!empty($crmId)) {
                            //查询客户标签
                            (new Lists())->where(['phone' => $rjdata['mobile']])->update(['crmId' => $crmId]);
                        }
                    } elseif (!empty($rjdata['mobile'])) {
                        (new Lists())->where(['phone' => $rjdata['mobile']])->update(['crmId' => 0]);
                    }
                }
            }
        }
        Log::write('----crmID更新end-----', 'coupon');

        //更新各品牌标签
        Log::write('----标签更新star-----', 'coupon');
        foreach ($list as $peizhi) {
            $rdsnames = 'crmidupdatessstagmss' . $peizhi['id'];
            $rdspeizhi = Redis::get($rdsnames);
            if ($rdspeizhi) {
                continue;
            }
            //更新各品牌crmID
            $crmId = (new Lists())->wherenotNull('crmId')->where('tagcreated', '<= time', $times)->where('createds', '>= time', $dates)->where(['type' => $peizhi['type'], 'isdel' => 1])->limit(199)->column('crmId');
            $crmId = array_filter($crmId);
            if (count($crmId) <= 0) {
                continue;
            }
            $crmId = implode(',', $crmId);
            //批量查询
            $ccdata = [
                "crmIds" => $crmId
            ];
            $ccjsonData = json_encode($ccdata);
            // 2. 请求服务器处理
            $ccurl = "https://open.workec.com/v2/customer/queryLabel";
            list($ccreturnCode, $ccreturnContent) = doPost($peizhi['cid'], $peizhi['appId'], $peizhi['appSecret'], $ccurl, $ccjsonData);
            $ccrjson = json_decode($ccreturnContent, true) ?? [];
            Log::write($ccrjson, 'coupon');
            Redis::setex($rdsnames, 3600, 3600);
            if (!empty($ccrjson['code']) && $ccrjson['code'] == 200 && !empty($ccrjson['data']) && count($ccrjson['data']) > 0) {
                foreach ($ccrjson['data'] as $tags) {
                    if (empty($tags['crmId']) || empty($tags['labelIds'])) {
                        continue;
                    }
                    $tags['labelIds'] = explode(',', $tags['labelIds']);
                    if (count($tags['labelIds']) <= 0) {
                        continue;
                    }
                    $labelId = 0;
                    $labeltext = [];
                    foreach ($tags['labelIds'] as $value) {
                        $labelId = $value;
                        $tag_name = (new Tags())->where(['type' => $peizhi['type'], 'labelId' => $value])->value('labelName') ?? '';
                        if (!empty($tag_name)) {
                            $labeltext[] = $tag_name;
                        }
                    }
                    $labeltext = implode(',', $labeltext);
                    $tagslist = (new Tags())->where(['type' => $peizhi['type'], 'labelId' => $labelId])->value('status') ?? 0;
                    Db::startTrans();
                    try {
                        (new Lists())->where(['type' => $peizhi['type'], 'crmId' => $tags['crmId']])->update(['youxiao' => $tagslist, 'yxtags' => $labeltext, 'tagcreated' => date('Y-m-d H:i:s')]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                    }
                }
            }
            //一个小时更新一次
        }
        Log::write('----标签更新end-----', 'coupon');

        //更新各品牌标签
        Log::write('----标签自动库更新star-----', 'eclist');
        //for ($i = 0; $i < 3000; $i++) {
            //sleep(4);
            foreach ($list as $peizhi) {
                $rdsnames = 'crmidupdatessstagmsszdk' . $peizhi['id'];
                $rdspeizhi = Redis::get($rdsnames);
                //判断次数，一分钟不能超过10次
                $number = 0;
                if ($rdspeizhi) {
                    $number = (int)$rdspeizhi ?? 0;
                }
                if ($number >= 5) {
                    continue;
                }
                Redis::setex($rdsnames, 5, $number + 1);
                //更新各品牌crmID
                $crmId = (new Exphone())->orderRaw('RAND()')->wherenotNull('crmId')->where(['type' => $peizhi['type'], 'youxiao' => 0])->limit(199)->column('crmId');
                $crmId = array_filter($crmId);
                if (count($crmId) <= 0) {
                    continue;
                }
                $crmId = implode(',', $crmId);
                //批量查询
                $ccdata = [
                    "crmIds" => $crmId
                ];
                $ccjsonData = json_encode($ccdata);
                // 2. 请求服务器处理
                $ccurl = "https://open.workec.com/v2/customer/queryLabel";
                list($ccreturnCode, $ccreturnContent) = doPost($peizhi['cid'], $peizhi['appId'], $peizhi['appSecret'], $ccurl, $ccjsonData);
                $ccrjson = json_decode($ccreturnContent, true) ?? [];
                Log::write($ccrjson, 'coupon');
                //if ($ccrjson['code'] == 200 && empty($ccrjson['data'])) {
                    $crmup = explode(',',$crmId);
                    (new Exphone())->where([
                        'type' => $peizhi['type'],
                        'crmId' => $crmup
                    ])->update(['youxiao' => 2]);
                //}
                if (!empty($ccrjson['code']) && $ccrjson['code'] == 200 && !empty($ccrjson['data']) && count($ccrjson['data']) > 0) {
                    foreach ($ccrjson['data'] as $tags) {
                        if (empty($tags['crmId']) || empty($tags['labelIds'])) {
                            continue;
                        }
                        $tags['labelIds'] = explode(',', $tags['labelIds']);
                        if (count($tags['labelIds']) <= 0) {
                            continue;
                        }
                        $labelId = 0;
                        $labeltext = [];
                        foreach ($tags['labelIds'] as $value) {
                            $labelId = $value;
                            $tag_name = (new Tags())->where(['type' => $peizhi['type'], 'labelId' => $value])->value('labelName') ?? '';
                            if (!empty($tag_name)) {
                                $labeltext[] = $tag_name;
                            }
                        }
                        $labeltext = implode(',', $labeltext);
                        $tagslist = (new Tags())->where(['type' => $peizhi['type'], 'labelId' => $labelId])->value('status') ?? 0;
                        if (empty($tagslist)) {
                            $tagslist = 2;
                        }
                        Db::startTrans();
                        try {
                            (new Exphone())->where(['type' => $peizhi['type'], 'crmId' => $tags['crmId']])->update(['youxiao' => $tagslist, 'yxtags' => $labeltext]);
                            Db::commit();
                        } catch (\Exception $e) {
                            dump($e->getMessage());
                            Db::rollback();
                        }
                    }
                }
                //一个小时更新一次
            }
        //}

    }
}
